package com.yiboshi.rehrs.exception;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.thread.ThreadUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.yiboshi.rehrs.common.VarConstant;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.config.ThreadLocalSession;
import com.yiboshi.rehrs.domain.entity.SmZhongUser;
import com.yiboshi.rehrs.exception.ZhongException;
import com.yiboshi.rehrs.helper.RedisLocker;
import com.yiboshi.rehrs.param.ZhongRes;
import com.yiboshi.rehrs.util.CacheUtils;
import com.yiboshi.rehrs.util.DingdingUtils;
import com.yiboshi.rehrs.util.ThreadPoolUtils;
import com.yiboshi.rehrs.util.WebUtils;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 功能：Controller统一控制器
 *
 * @author Negi
 * @version 2018-08
 */
@SuppressWarnings("checked")
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class ControllerExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    RedisLocker redisLocker;


    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ZhongRes mismatchErrorHandler(Exception e, HttpServletRequest request, HttpServletResponse response) {
        if(!ThreadLocalSession.getHeaderAuthValid()){
            //封禁ip
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        log.error("", e);
        return ZhongRes.fail("系统异常，请稍后再试");
    }

 /*   @ExceptionHandler({MissingPathVariableException.class})
    @ResponseBody
    public ZhongRes mismatchErrorHandler(MissingPathVariableException e, HttpServletRequest request) {
        log.error("uri:{}",request.getRequestURI(), e.getMessage());
        return null;
    }*/

    @ExceptionHandler(MissingPathVariableException.class)
    public ResponseEntity<String> handleMissingPathVariable(MissingPathVariableException ex, HttpServletRequest request) {
        //String error = "缺少路径参数: " + ex.getVariableName();
        log.error("MissingPathVariableException,uri:{}",request.getRequestURI());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<String> MissingServletRequestParameterException(MissingPathVariableException ex, HttpServletRequest request) {
        //String error = "缺少路径参数: " + ex.getVariableName();
        log.error("MissingServletRequestParameterException,uri:{}",request.getRequestURI());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("");
    }





    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseBody
    public ZhongRes HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request,
                                                           HttpServletResponse response ) {
       /*if(RehrsSystemConfig.getProfile().equalsIgnoreCase("ali81")){
           Cache<String, Object> cache = CacheUtils.builder(30);
           AtomicInteger cacheObj = (AtomicInteger) cache.get("MethodNotSupported",(s)->new AtomicInteger(0));
           cacheObj.incrementAndGet();
           if(cacheObj.get()>100){

               cacheObj.set(0);
               cache.invalidateAll();
               ProcessBuilder processBuilder = new ProcessBuilder();
               processBuilder.command("/bin/bash", "-c", "firewall-cmd --zone=public --remove-port=80/tcp --permanent && firewall-cmd --reload");
               processBuilder.redirectErrorStream(true);

               try {
                   Process process = processBuilder.start();
                   int exitCode = process.waitFor();
                   if (exitCode != 0) {
                       log.error("防火墙命令执行失败，退出码: {}", exitCode);
                   }else{
                       log.info("服务器收到攻击，APP暂停使用");
                       redisLocker.delLock(VarConstant.FIREWALL_DINGDING);
                   }

               } catch (Exception ex) {
                   log.error("执行防火墙命令异常", ex);
               }
           }
       }*/
        String ipAddress = WebUtils.getIpAddress(request);
        log.error("MethodNotSupported,uri:{} ,method:{},ipAddress:{}",request.getRequestURI(),request.getMethod(),ipAddress);
        // 设置403状态码
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }




    @ExceptionHandler({ZhongException.class})
    @ResponseBody
    public ZhongRes mismatchErrorHandler(ZhongException e, HttpServletRequest request) {
        log.error("", e);
        //SmZhongUser smUserInfo = ThreadLocalSession.getSmUserInfo();
        String message = e.getMessage();
        if(request.getRequestURI().contains("/smf/")){
            message = message.replace("授权","服务");
        }
        return new ZhongRes(e.getCode(),message);
    }

}